package service;

import com.alibaba.fastjson.JSON;
import mapper.CommonMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.multipart.MultipartFile;
import pojos.common.DocHelper;
import pojos.common.ReplyMessage;
import pojos.common.SubjectInfo;
import pojos.subject.ClassInfoManager;
import pojos.subject.UserRelationshipManager;

import java.io.File;
import java.sql.Timestamp;
import java.util.List;
import java.util.UUID;

/**
 * 公共接口服务类
 */
public class CommonUtilsService {

    private Logger logger = LoggerFactory.getLogger(CommonUtilsService.class);
    private CommonMapper commonMapper;

    @Value("${yd.img.path}")
    private String avatarPath;

    @Autowired
    public CommonUtilsService(CommonMapper commonMapper) {
        this.commonMapper = commonMapper;
    }

    /**
     * 修改头像
     */
    public ReplyMessage alterAvatar(MultipartFile avatarFile, String userAvatarPath, int userId, int type){
        String fileName = avatarFile.getOriginalFilename();
        String targetPath = UUID.randomUUID().toString().replace("-","") + fileName.substring(fileName.lastIndexOf("."));

        File imageFile = new File(avatarPath + targetPath);
        if( !imageFile.exists() ){
            imageFile.mkdirs();
        }

        ReplyMessage replyMessage = new ReplyMessage();
        try {
            avatarFile.transferTo(imageFile);

            // 删除原头像
            File sourceFile = new File(avatarPath + userAvatarPath);
            if(sourceFile.exists()){
                sourceFile.delete();
            }

            // 更新数据库信息
            switch (type){
                // 管理员
                case 1:{
                    commonMapper.updateAdminAvatar(userId, targetPath);
                    break;
                }
                // 老师
                case 2:{
                    commonMapper.alterTeacherAvatar(userId,targetPath);
                    break;
                }
                // 学生
                case 3:{
                    commonMapper.alterStudentAvatar(userId,targetPath);
                    break;
                }
                // 家长
                case 4:{
                    commonMapper.alterParentsAvatar(userId,targetPath);
                    break;
                }
                default:{
                    replyMessage.setStatus(400);
                    replyMessage.setInfo("上传失败！");
                    return replyMessage;
                }
            }

            replyMessage.setStatus(200);
            replyMessage.setInfo(targetPath);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("修改用户头像失败，类型："+type+"，用户ID："+userId+"，文件名："+fileName);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 查询所有可用科目信息
     */
    public ReplyMessage queryAllEnaSubjects(){
        ReplyMessage replyMessage = new ReplyMessage();
        try {
            List<SubjectInfo> subjectInfos = commonMapper.queryAllEnaSubjectInfo();
            if(subjectInfos != null){
                replyMessage.setStatus(200);
                replyMessage.setInfo(JSON.toJSONString(subjectInfos));
            }else{
                replyMessage.setStatus(400);
                replyMessage.setInfo("未查询到任何信息！");
            }
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询可用的科目信息失败！");

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 查询所有科目信息
     */
    public List<SubjectInfo> queryAllSubjectInfo(){
        try {
            return commonMapper.queryAllSubjectInfo();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询所有科目信息异常！");

            return null;
        }
    }

    /**
     * 查找特定的科目信息
     */
    public ReplyMessage querySubjectById(int id){
        ReplyMessage replyMessage = new ReplyMessage();
        try {
            SubjectInfo subjectInfo = commonMapper.querySubjectById(id);
            if(subjectInfo != null){
                replyMessage.setStatus(200);
                replyMessage.setInfo(JSON.toJSONString(subjectInfo));
                return replyMessage;
            }

            replyMessage.setStatus(400);
            replyMessage.setInfo("查询结果为空！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("根据ID查找科目信息异常！ID："+id);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 查询用户关系
     */
    public List<UserRelationshipManager> queryAllRelation(){
        try {
            return commonMapper.queryAllUserRelationship();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询所有的用户关系异常！");

            return null;
        }
    }

    /**
     * 查找特定的用户关系
     */
    public UserRelationshipManager queryUserRelationship(int id){
        try {
            return commonMapper.queryUserRelationship(id);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查找用户关系异常，关系ID："+id);

            return null;
        }
    }

    /**
     * 保存用户Cookies
     */
    public void updateUserCookies(String role, int id, String cookies, long cookiesTime){
        try {
            commonMapper.updateUserCookies(role,id,cookies,cookiesTime);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("更新用户Cookies时异常，用户角色："+role+"，用户ID："+id);
        }
    }

    /**
     * 教师课程信息查询
     */
    public ReplyMessage teacherQueryClassInfo(int teacherId){
        ReplyMessage replyMessage = new ReplyMessage();
        try {
            List<ClassInfoManager> classInfoManagerList = commonMapper.teacherClassInfo(teacherId,1);
            if(classInfoManagerList != null){
                replyMessage.setInfo(JSON.toJSONString(classInfoManagerList));
                replyMessage.setStatus(200);
                return replyMessage;
            }
            replyMessage.setStatus(400);
            replyMessage.setInfo("查询结果为空！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("教师查询课程信息异常，教师ID："+teacherId);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 学生课程信息查询
     */
    public ReplyMessage studentClassInfoQuery(int studentId){
        ReplyMessage replyMessage = new ReplyMessage();

        try {
            List<ClassInfoManager> classInfoManagerList = commonMapper.studentClassInfo(studentId,1);
            if(classInfoManagerList != null){
                replyMessage.setStatus(200);
                replyMessage.setInfo(JSON.toJSONString(classInfoManagerList));
                return replyMessage;
            }
            replyMessage.setStatus(400);
            replyMessage.setInfo("查询结果为空！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("查询学生课程信息异常，学生ID："+studentId);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 家长查询课程信息
     */
    public ReplyMessage parentsClassInfo(int parentsId){
        ReplyMessage replyMessage = new ReplyMessage();

        try {
            List<ClassInfoManager> classInfoManagerList = commonMapper.parentsClassInfo(parentsId,1);
            if(classInfoManagerList != null){
                replyMessage.setStatus(200);
                replyMessage.setInfo(JSON.toJSONString(classInfoManagerList));
                return replyMessage;
            }
            replyMessage.setStatus(400);
            replyMessage.setInfo("查询结果为空！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("家长查询课程信息异常，家长ID："+parentsId);

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 查找所有的帮助文档
     */
    public ReplyMessage queryAllDoc(){
        ReplyMessage replyMessage = new ReplyMessage();
        try {
            List<DocHelper> docHelperList = commonMapper.queryDocInfo();
            if(docHelperList != null){
                replyMessage.setStatus(200);
                replyMessage.setInfo(JSON.toJSONString(docHelperList));
                return replyMessage;
            }
            replyMessage.setStatus(400);
            replyMessage.setInfo("查询结果为空！");
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("管理员查询所有的帮助文档异常！");

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 添加文档
     */
    public ReplyMessage addDocument(DocHelper docHelper){
        docHelper.setAddTime(new Timestamp(System.currentTimeMillis()));
        docHelper.setAlterTime(new Timestamp(System.currentTimeMillis()));

        ReplyMessage replyMessage = new ReplyMessage();
        try {
            commonMapper.addDocument(docHelper);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("管理员添加文档异常！");

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }

    /**
     * 查询单个文档信息
     */
    public DocHelper queryDocInfoById(int docId){
        try {
            return commonMapper.queryDocById(docId);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("管理员查询文档信息异常，文档ID："+docId);

            return null;
        }
    }

    /**
     * 修改文档
     */
    public ReplyMessage updateDoc(DocHelper docHelper){
        docHelper.setAlterTime(new Timestamp(System.currentTimeMillis()));

        ReplyMessage replyMessage = new ReplyMessage();
        try {
            commonMapper.updateDocument(docHelper);
            replyMessage.setStatus(200);
            return replyMessage;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("管理员修改文档异常，文档ID："+docHelper.getId());

            replyMessage.setStatus(500);
            replyMessage.setInfo("服务器异常，请稍后重试！");
            return replyMessage;
        }
    }
}
